﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media;
namespace _47WPFDataBindingIValueConverter
{
    public class StringColorConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if(targetType == typeof(string))
            {
                string str = value as string;
                if (str == "Red")
                    return "Đỏ";
                else if (str == "Green")
                    return "Xanh lá";
                else if (str == "Blue")
                    return "Xanh biển";
                else
                    return "Không biết";                 
            
            }
            else if (targetType == typeof(Brush))
            {
                string str = value as string;
                try 
                { 
                    Color color = (Color)ColorConverter.ConvertFromString(str);
                    return new SolidColorBrush(color);               
                }catch(Exception ex)
                {
                    return DependencyProperty.UnsetValue;
                }            
            }
            return DependencyProperty.UnsetValue;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
            if (targetType == typeof(string))
            {
                string str = value as string;
                if (str == "Đỏ")
                    return "Red";
                else if (str == "Xanh lá")
                    return "Green";
                else if (str == "Xanh biển")
                    return "Blue";
                else
                    return "Unknow";

            }
            else if (targetType == typeof(Brush))
            {
                string str = value as string;
                if (str == "Đỏ")
                    str= "Red";
                else if (str == "Xanh lá")
                    str= "Green";
                else if (str == "Xanh biển")
                    str= "Blue";
                else
                    str= "Unknow";

                try
                {
                    Color color = (Color)ColorConverter.ConvertFromString(str);
                    return new SolidColorBrush(color);
                }
                catch (Exception ex)
                {
                    return DependencyProperty.UnsetValue;
                }
            }
            return DependencyProperty.UnsetValue;
        }
    }
}
